package com.example.dev_demo.excel.demo;

import com.example.dev_demo.excel.imports.ExcelErrorCommentUtil;
import com.example.dev_demo.excel.imports.ExcelImportUtil;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/excel")
public class ExcelImportController {

    // 表头与实体字段的映射关系
    private static final Map<String, String> HEADER_FIELD_MAP;

    static {
        HEADER_FIELD_MAP = new HashMap<>();
        HEADER_FIELD_MAP.put("用户名", "username");
        HEADER_FIELD_MAP.put("手机号", "phone");
        HEADER_FIELD_MAP.put("年龄", "age");
        HEADER_FIELD_MAP.put("邮箱", "email");
        HEADER_FIELD_MAP.put("密码", "password");
    }

    /**
     * 导入Excel并验证数据，返回错误信息用于前端展示
     */
    @PostMapping("/validate-for-display")
    public ResponseEntity<?> validateForDisplay(@RequestParam("file") MultipartFile file) {
        try (InputStream is = file.getInputStream()) {
            //校验导入Excel
            ExcelImportUtil.ImportResult<User> result =
                    ExcelImportUtil.parseAndValidateExcel(is, User.class, HEADER_FIELD_MAP, 1);

            //校验未通过判断
            if (result.hasErrors()) {
                // 按行号分组错误信息，便于前端展示
                Map<Integer, List<ExcelImportUtil.ImportError>> errorsByRow =
                        ExcelImportUtil.groupErrorsByRow(result.getErrorList());
                return ResponseEntity.ok(MapUtils.of(
                        "success", false,
                        "message", "数据校验失败",
                        "errors", errorsByRow
                ));
            } else {
                // 校验通过，可以进行后续处理
                return ResponseEntity.ok(MapUtils.of(
                        "success", true,
                        "message", "数据校验通过",
                        "dataList", result.getDataList(),
                        "dataCount", result.getDataList().size()
                ));
            }
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(MapUtils.of("success", false, "message", "处理失败: " + e.getMessage()));
        }
    }

    /**
     * 导入Excel并验证数据，生成带错误批注的Excel供下载
     */
    @PostMapping("/validate-for-download")
    public void validateForDownload(@RequestParam("file") MultipartFile file, HttpServletResponse response) throws IOException {
        // 1. 表头行位置
        int headerRowNum = 1;
        // 2. 解析并校验Excel
        ExcelImportUtil.ImportResult<User> result = ExcelImportUtil.parseAndValidateExcel(
                file.getInputStream(), User.class, HEADER_FIELD_MAP, headerRowNum);

        // 3. 若有错误，添加批注并原样并下载
        if (result.hasErrors()) {
            ExcelErrorCommentUtil.addErrorComments(response, file, result.getErrorList(), headerRowNum, "用户信息导入");
        } else {
            // 无错误时的处理（如返回成功信息）
            response.getWriter().write("数据验证通过，无错误");
        }
    }

    /**
     * 导入并保存验证通过的数据
     */
    @PostMapping("/import")
    public ResponseEntity<?> importData(@RequestParam("file") MultipartFile file) {
        try (InputStream is = file.getInputStream()) {
            ExcelImportUtil.ImportResult<User> result =
                    ExcelImportUtil.parseAndValidateExcel(is, User.class, HEADER_FIELD_MAP, 1);

            if (result.hasErrors()) {
                return ResponseEntity.badRequest().body(MapUtils.of(
                        "success", false,
                        "message", "数据存在错误，请修正后重新导入",
                        "errorCount", result.getErrorList().size(),
                        "errorList",result.getErrorList()
                ));
            }

            // 保存数据到数据库
            saveDataToDatabase(result.getDataList());

            return ResponseEntity.ok(MapUtils.of(
                    "success", true,
                    "message", "数据导入成功",
                    "importCount", result.getDataList().size()
            ));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(MapUtils.of("success", false, "message", "导入失败: " + e.getMessage()));
        }
    }

    /**
     * 将验证通过的数据保存到数据库
     */
    private void saveDataToDatabase(List<User> userList) {
        // 实际项目中实现数据库保存逻辑
        // 例如：userRepository.saveAll(userList);
    }
}
    